package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.CheckGroupDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.CheckGroup;
import com.itheima.service.CheckGroupervice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = CheckGroupervice.class)
@Transactional
public class CheckGroupServiceImpl implements CheckGroupervice {
    @Autowired
    private CheckGroupDao checkGroupDao;

    @Override
    public void add(CheckGroup checkGroup, Integer[] checkitemIds) {
        checkGroupDao.add(checkGroup);
        Integer checkGroupId = checkGroup.getId();

        addConnection(checkitemIds, checkGroupId);

    }

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        //做分页处理
        PageHelper.startPage(currentPage, pageSize);

        Page<CheckGroup> checkGroupPage = checkGroupDao.findPage(queryString);
        return new PageResult(checkGroupPage.getTotal(), checkGroupPage.getResult());
    }

    @Override
    public CheckGroup findById(Integer id) {

        return checkGroupDao.findById(id);
    }

    @Override
    public List<Integer> findCheckGroupIdsByCheckItemId(Integer id) {

        return checkGroupDao.findCheckGroupIdsByCheckItemId(id);
    }

    @Override
    public void edit(Integer[] checkitemIds, CheckGroup checkGroup) {
        //修改检查组表
        checkGroupDao.edit(checkGroup);
        //删除中间表关联关系
        checkGroupDao.deleteConnection(checkGroup.getId());
        //添加中间表关联关系
        addConnection(checkitemIds,checkGroup.getId());

    }

    @Override
    public List<CheckGroup> findAll() {
        return checkGroupDao.findAll();
    }

    @Override
    public void deleteConnection(Integer id) {
        checkGroupDao.deleteConnection(id);
    }

    @Override
    public void delete(Integer id) {
        checkGroupDao.delete(id);
    }

    /**
     * 抽取添加关联方法
     *
     * @param checkitemIds
     * @param checkGroupId
     */
    public void addConnection(Integer[] checkitemIds, Integer checkGroupId) {
        if (checkitemIds != null && checkitemIds.length > 0) {
            for (Integer checkitemId : checkitemIds) {
                Map<String, Integer> map = new HashMap<>();
                map.put("checkGroupId", checkGroupId);
                map.put("checkitemId", checkitemId);
                checkGroupDao.setCheckGroupIdAndCheckItemId(map);
            }
        }
    }
}

